/**
 1. ng g service services/storage

 2. app.module.ts里面引入 创建的服务并且声明
 // 引入并且配置服务
 import {StorageService} from "./services/storage.service";
 providers: [StorageService],  // 配置服务

 3. 在用到的组件里面

 // 引入服务
 import {StorageService} from "../../services/storage.service";
 //初始化
 constructor(public storage:StorageService) {
    let s = this.storage.get()
    console.log(s)
  }

 然后我们就可以在组件的任何地方使用这个服务了
 */

import { Component, OnInit } from '@angular/core';

// 引入服务
import {StorageService} from "../../services/storage.service";

/*
不建议这样使用
let storage = new StorageService();
console.log(storage)
*/

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {

  public keyword:string;

  public historyList:any[]=[];

  //官方引入服务的方法
  constructor(public storage:StorageService) {
    // let s = this.storage.get()
    // console.log(s)
  }

  ngOnInit(): void {
    console.log('页面刷新会触发这个生命周期函数')

    let searchList = this.storage.get('searchList')

    if(searchList) {
      this.historyList = searchList
    }
  }

  doSearch() {
    if(this.historyList.indexOf(this.keyword)==-1) {
      this.historyList.push(this.keyword)

      this.storage.set('searchList', this.historyList)
    }

    this.keyword=''
    console.log(this.keyword)
  }

  deleteHistory(key) {
    this.historyList.splice(key, 1)

    this.storage.set('searchList', this.historyList)
  }

}
